package com.warren.blog.testkafaka;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;

/**
 * @author warren
 * @data: 2022/3/29 2:01 PM
 * @decription: kfaka producer
 */
public class CustomProducerTranactions {
    public static void main(String[] args) {
        //0配置
        Properties properties = new Properties();
        //连接集群bootstrap.servers
        properties.put("bootstrap.servers", "192.168.1.9:9092");
//        ProducerConfig.BOOTSTRAP_SERVERS_CONFIG
        //指定key和value的序列化类型key.serializer
//        ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG
//        ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG
        properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        //必须指定事物id
        properties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "tranaction_id_01");

        //1.创建kafka生产者对象
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);
        //2.发送数据

        kafkaProducer.initTransactions();
        kafkaProducer.beginTransaction();
        try {
            for (int i = 0; i < 5; i++) {
                kafkaProducer.send(new ProducerRecord<>("test1", "test tranactions" + i));
            }
            kafkaProducer.commitTransaction();
        } catch (Exception e) {
            kafkaProducer.close();
        }
        kafkaProducer.close();
    }
}
